<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "comments".
 *
 * @property integer $id
 * @property string $uid
 * @property string $body
 * @property string $type
 * @property string $rid
 * @property string $status
 * @property string $created_at
 */
class Comments extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'comments';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['body'], 'required'],
            [['body'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'uid' => '用户ID',
            'body' => '评论内容',
            'type' => '类型',
            'rid' => '关联ID',
            'best_answer' => '最佳答案',
            'status' => '状态',
            'created_at' => '创建时间',
        ];
    }

    /**
     * 获取评论用户信息
     * @return type
     */
    public function getAuthor() {
        return $this->hasOne(Users::className(), ['id' => 'uid']);
    }

    public function Content($type, $rid) {
        switch ($type) {
            case 'qa':
                $content = Qa::findOne($rid);
                break;
            case 'article':
                $content = Article::findOne($rid);
                break;
            default:
                $content = '';
        }
        return $content;
    }

    /**
     * 在插入之前操作
     * @param type $insert
     * @return type
     */
    public function beforeSave($insert) {
        if ($this->isNewRecord) {
            $this->uid = Yii::$app->user->identity->id;
            $this->status = '1';
            $this->created_at = time();
        } else {
            
        }
        return parent::beforeSave($insert);
    }

    /**
     * 插入之后操作
     * 添加评论增加声望
     * @param type $insert
     */
    public function afterSave($insert, $changedAttributes) {
        if ($this->isNewRecord) {
            Users::add_prestige(3, Yii::$app->user->identity->id); //添加评论增加3点声望
        }
        parent::afterSave($insert, $changedAttributes);
    }

}
